import datetime
import logging 

import webapp2
from google.appengine.ext import blobstore

def deleteFilesOlderThanBasetime(basetime):
    '''
    search and delete files older than basetime
    '''
    basetime = basetime.strftime('%Y-%m-%d %H:%M:%S')
    logging.debug('basetime: ' + basetime)
    
    query = blobstore.BlobInfo.gql("WHERE filename = :1 AND creation < DATETIME( :2 )", 'korean_twitter_sample', basetime)
    
    count = 0
    while True:
        blob = None
        for blob in query.run(limit = 100): # to avoid 60 seconds deadline for Datastore to return a result
            blob.delete()
            count += 1
        if not blob: break

    logging.debug('the number of deleted files = ' + str(count))
    
    return

class DeleteKoreanTwitterSampleFiles(webapp2.RequestHandler):
    '''
    delete twitter_sample_* files created before basetime 
    '''
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        # a parameter 'basetime' whose format is '%Y%m%d' and default is the last day.
        if self.request.get('basetime'):
            basetime = self.request.get('basetime')
            basetime = datetime.datetime.strptime(basetime, '%Y%m%d')
        else:
            basetime = datetime.datetime.now() - datetime.timedelta(days = 1)
            basetime = basetime.replace(hour = 0, minute = 0, second = 0, microsecond = 0)

        deleteFilesOlderThanBasetime(basetime)
        
        return
        
app = webapp2.WSGIApplication([('/delete_korean_twitter_sample_files', DeleteKoreanTwitterSampleFiles)], debug = True)
